---
id: switch
title: Switch
description: A control element that allows for a binary selection.
---

<ComponentPreview id="Switch" />

## Anatomy

To set up the switch correctly, you'll need to understand its anatomy and how we name its parts.

> Each part includes a `data-part` attribute to help identify them in the DOM.

<Anatomy id="switch" />

### Design impact on the asChild property

The `Switch.Root` element of the switch is a `label` element. This is because the switch is a form control and should be
associated with a label to provide context and meaning to the user. Otherwise, the HTML and accessibility structure will
be invalid.

> If you need to use the `asChild` property, make sure that the `label` element is the direct child of the `Switch.Root`
> component.

## Examples

Learn how to use the `Switch` component in your project. Let's take a look at the most basic example:

<Example id="basic" />

### Controlled Switch

For a controlled Switch component, the state of the toggle is managed using the checked prop, and updates when the
`onCheckedChange` event handler is called:

<Example id="controlled" />

### Render Prop Usage

The Switch component also allows for a render prop, granting direct access to its internal state. This enables you to
dynamically adjust and customize aspects of the component based on its current state:

<Example id="render-prop" />

### Using the Field Component

The `Field` component helps manage form-related state and accessibility attributes of a switch. It includes handling
ARIA labels, helper text, and error text to ensure proper accessibility.

<Example id="with-field" />

### Using the Root Provider

The `RootProvider` component provides a context for the switch. It accepts the value of the `useSwitch` hook. You can
leverage it to access the component state and methods from outside the switch.

<Example id="root-provider" />

> If you're using the `RootProvider` component, you don't need to use the `Root` component.

## API Reference

### Props

<ComponentTypes id="switch" />

### Context

These are the properties available when using `Switch.Context`, `useSwitchContext` hook or `useSwitch` hook.

<ContextType id="switch" />

## Accessibility

Complies with the [Switch WAI-ARIA design pattern](https://www.w3.org/WAI/ARIA/apg/patterns/switch/).

### Keyboard Support

<KeyBindingsTable id="switch" />
